<template>
  <div class="search">
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search
        v-model="userKey"
        placeholder="请输入搜索关键词"
        shape="round"
      >
      </van-search>
      <div @click="onSearch">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <p  v-for='(v,i) in historyList' :key='i' @click="onSearch($event,v)">{{v}}</p>
    </div>
    <div class="historyList">
      <h2>搜索结果</h2>
      <router-link :to="'/articleDetail/' + v.id" v-for='(v,i) in searchList' :key='i'>{{v.title}}</router-link>
    </div>
  </div>
</template>

<script>
import {searchArticles} from '@/apis/article.js'
export default {
  data(){
    return {
      userKey:'',       //用户输入的关键字
      searchList:[],    //本次搜索的结果
      historyList:[],   //搜索历史记录
    }
  },
  methods:{
    async onSearch(e,value){
      if(value){
        this.userKey = value
      }
      let res = await searchArticles(this.userKey)
      console.log(res);
      this.searchList = res.data.data

      // 判断数组中是否已有当前关键字
      let index = this.historyList.indexOf(this.userKey)
      if(index !== -1){
      this.historyList.splice(index,1)
      }

      // 将当前用户关键字存储到本地存储
      this.historyList.unshift(this.userKey)
      localStorage.setItem('hm_toutiao_history',JSON.stringify(this.historyList))
      this.userKey = ''
    }
  },
  mounted () {
    // 历史记录的键：hm_toutiao_history
      // if(localStorage.getItem('hm_toutiao_history')){
      //   this.historyList = JSON.parse(localStorage.getItem('hm_toutiao_history'))
      // }
        this.historyList = JSON.parse(localStorage.getItem('hm_toutiao_history') || '[]')
  }
}
</script>

<style lang='less' scoped>
  .header{
    display: flex;
    height: 50px;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    border-bottom: 1px solid #ccc;
    .van-search{
      flex: 1;
      padding: 5px 12px;
    }
  }
  .historyList{
    padding:10px;
    border-bottom: 1px solid #ccc;
    h2{
      line-height: 40px;
      font-weight: bold;
    }
    > a {
      display: block;
      text-decoration: underline;
      line-height: 30px;
      color:#666;
    }
  }
</style>